<template>
    <el-form label-suffix=":" v-loading="loading" :model="formData" :rules="editable ? formRules : {}" ref="formRef"
        label-width="120px">
        <vp-card>
            <template #header>
                <vp-label zh="基础信息" en="Basic Information" />
            </template>
            <el-row>
                <vp-col :span="2">
                    <el-form-item prop="lx">
                        <template #label><vp-label zh="类型" en="Report No." /></template>
                        <el-radio-group v-if="editable" v-model="formData.lx" size="small">
                            <el-radio :label="10">固定翼</el-radio>
                            <el-radio :label="20">旋翼</el-radio>
                        </el-radio-group>
                        <span v-else>{{ formData.lx == 10 ? '固定翼' : formData.lx == 20 ? '旋翼' : '' }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="2">
                    <el-form-item prop="jx">
                        <template #label><vp-label zh="机型" en="Incident Process" /></template>
                        <el-input v-if="editable" v-model="formData.jx" maxlength="100" />
                        <span v-else>{{ formData.jx }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="2">
                    <el-form-item prop="xh">
                        <template #label><vp-label zh="型号" en="Incident Process" /></template>
                        <el-input v-if="editable" v-model="formData.xh" maxlength="100" />
                        <span v-else>{{ formData.xh }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="2">
                    <el-form-item prop="zzjx">
                        <template #label><vp-label zh="执照机型" en="Incident Process" /></template>
                        <el-input v-if="editable" v-model="formData.zzjx" maxlength="100" />
                        <span v-else>{{ formData.zzjx }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="1">
                    <el-form-item prop="sccj">
                        <template #label><vp-label zh="生产厂家" en="Incident Process" /></template>
                        <el-input v-if="editable" v-model="formData.sccj" maxlength="100" />
                        <span v-else>{{ formData.sccj }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>

        <vp-card>
            <template #header>
                <vp-label zh="主要部件" en="Basic Information" />
            </template>
            <el-row>
                <vp-col :span="1">
                    <el-form-item label-width="0px">
                        <el-checkbox-group v-model="formData.selectCheckedList" @change="handleComponentChange">
                            <el-checkbox v-for="item in componentTypes" :key="item.key" :label="item.key"
                                class="checkbox-item" :disabled="(item.key == 10 || item.key == 20) || !editable">
                                {{ item.name }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </vp-col>
            </el-row>
            <template v-for="(item, key) in formData.positionList" :key="key">
                <el-divider content-position="left">
                    {{ getComponentName(key) }}
                </el-divider>
                <el-row>
                    <vp-col :span="2">
                        <el-form-item :prop="`positionList.${key}.xingh`">
                            <template #label><vp-label zh="型号" en="Incident Process" /></template>
                            <el-input v-if="editable" v-model="item.xingh" maxlength="100" />
                            <span v-else>{{ item.xingh }}</span>
                        </el-form-item>
                    </vp-col>
                    <vp-col :span="2" v-if="key == 10">
                        <el-form-item :prop="`positionList.${key}.zjsl`" :rules="formRules.zjsl">
                            <template #label><vp-label zh="数量" en="Incident Process" /></template>
                            <el-input-number v-if="editable" v-model="item.zjsl" :min="1" :max="10" />
                            <span v-else>{{ item.zjsl }}</span>
                        </el-form-item>
                    </vp-col>
                    <vp-col :span="2" v-else>
                        <el-form-item :prop="`positionList.${key}.jh`">
                            <template #label><vp-label zh="件号" en="Incident Process" /></template>
                            <el-input v-if="editable" v-model="item.jh" maxlength="100" />
                            <span v-else>{{ item.jh }}</span>
                        </el-form-item>
                    </vp-col>
                </el-row>
                <el-row>
                    <vp-col :span="1">
                        <el-form-item :prop="`positionList.${key}.sccj`">
                            <template #label><vp-label zh="生产厂家" en="Incident Process" /></template>
                            <el-input v-if="editable" v-model="item.sccj" maxlength="100" />
                            <span v-else>{{ item.sccj }}</span>
                        </el-form-item>
                    </vp-col>
                </el-row>
            </template>
        </vp-card>

        <vp-card>
            <template #header>
                <vp-label zh="监控项目" en="Basic Information" />
            </template>
            <vp-vxe-table id="positionId" ref="tableRef" :data="formData.monitorList" row-key="id" minHeight="300">
                <vxe-column field="jklmc" title="项目 Problem No.">
                    <template #header><vp-label zh="项目" en="Problem No." /></template>
                    <template #default="{ row }">
                        <el-checkbox v-model="row.checked" :disabled="!editable" />
                        {{ row.jklmc }}
                    </template>
                </vxe-column>
                <vxe-column field="sjgs" title="格式 Insp. Date">
                    <template #header><vp-label zh="格式" en="Insp. Date" /></template>
                    <template #default="{ row }">
                        <template v-if="row.checked && row.jkflbh == '2T'">
                            <el-radio-group v-model="row.sjgs" :disabled="!editable">
                                <el-radio :value="10">小时分钟</el-radio>
                                <el-radio :value="20">小数点</el-radio>
                            </el-radio-group>
                        </template>
                    </template>
                </vxe-column>
                <vxe-column field="ws" title="小数点 Insp. Unit">
                    <template #header><vp-label zh="小数点" en="Insp. Unit" /></template>
                    <template #default="{ row }">
                        <template
                            v-if="row.checked && (row.jkflbh == '3C' || (row.jkflbh == '2T' && row.sjgs == 20) || row.jkflbh == '4N')">
                            <el-input-number v-model="row.ws" :min="1" :max="3"
                                :disabled="row.jkflbh == '3C' || !editable" />
                        </template>
                    </template>
                </vxe-column>
                <vxe-column field="jkdw" title="单位 Insp. Person">
                    <template #header><vp-label zh="单位" en="Insp. Person" /></template>
                    <template #default="{ row }">
                        <template v-if="row.checked">
                            <el-input v-model="row.jkdw" placeholder="请输入" v-if="editable" />
                            <span v-else>{{ row.jkdw }}</span>
                        </template>
                    </template>
                </vxe-column>
            </vp-vxe-table>


        </vp-card>

    </el-form>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, toRefs } from 'vue'
import validateUtils from '/@/utils/validateUtils';
import { verifiyNumberInteger, verifyCnAndSpace } from '/@/utils/toolsValidate';

import { componentTypes, ComponentItem } from '/@/utils/enums';
export type { ComponentItem } from '/@/utils/enums';

import request from '/@/utils/request';
import { useRouter } from 'vue-router';

export default defineComponent({
    name: 'abnormalList',
    props: {
        type: {
            type: String,
            default: 'add',
        }
    },
    setup(props) {
        const state = reactive({
            loading: false,
            saveLoading: false,
            csid: '',
            csmc: '',
            formData: {
                id: '',
                zt: null,
                lx: null,
                jx: "",
                xh: "",
                zzjx: "",
                sccj: "",

                selectCheckedList: [10, 20],
                positionList: {
                    10: {
                        mainid: "",
                        wz: 10,
                        zjsl: null,
                        xingh: "",
                        jh: "",
                        sccj: "",
                    },
                    20: {
                        mainid: "",
                        wz: 10,
                        zjsl: null,
                        xingh: "",
                        jh: "",
                        sccj: "",
                    }
                } as any,
                monitorList: [] as any[],
            },
            formRules: {
                lx: [validateUtils.notNull],
                jx: [validateUtils.notNull],
                zjsl: [validateUtils.notNull],
            },

            //监控项目
            monitorInitList: {} as any,

            componentTypes: componentTypes,
        });

        const editable = computed(() => {
            return props.type === 'add' || props.type === 'edit';
        })

        const initFormData = () => {
            state.formData = {
                id: '',
                zt: null,
                lx: null,
                jx: "",
                xh: "",
                zzjx: "",
                sccj: "",

                selectCheckedList: [10, 20],
                positionList: {
                    10: {
                        mainid: "",
                        wz: 10,
                        zjsl: null,
                        xingh: "",
                        jh: "",
                        sccj: "",
                    },
                    20: {
                        mainid: "",
                        wz: 10,
                        zjsl: null,
                        xingh: "",
                        jh: "",
                        sccj: "",
                    }
                } as any,
                monitorList: [] as any[],
            }
        }
        const formRef = ref();
        /**
         * 设置页面数据
         */
        const setData = async (formData: any) => {
            let res = await request.get(`/basicData/monitorInit/list`)
            state.monitorInitList = res.data;

            initFormData();
            state.formData = {
                ...state.formData,
                ...formData,
            };

            initMonitorList();
        }

        /**
         * 获取页面数据
         * @param zt 状态
         */
        const getData = (): Promise<any> => {
            let promise = new Promise((resolve, reject) => {
                formRef.value.validate((valid: boolean) => {
                    if (valid) {
                        resolve({
                            ...state.formData,
                        });
                    } else {
                        reject();
                    }
                })
            })
            return promise;
        }

        const initMonitorList = () => {
            // 1. 先筛选出基础保留项（wz在选中列表中）
            const baseRetainedItems = state.formData.monitorList
                .filter(item => state.formData.selectCheckedList.includes(item.wz));

            // 2. 对每个选中的wz，补充保留项中缺失的jklbh项
            const processedRetainedItems = [...baseRetainedItems];

            // 遍历所有需要处理的wz（selectCheckedList中的）
            state.formData.selectCheckedList.forEach(wz => {
                // 获取当前wz在monitorInitList中的所有基准项
                const sameLevelInitItems = state.monitorInitList[wz] as any[] || [] ;
                if (sameLevelInitItems.length === 0) return;

                // 获取当前wz在基础保留项中的所有项
                const retainedItemsForWz = baseRetainedItems.filter(item => item.wz === wz);
                // 提取这些保留项已有的jklbh（用于判断缺失）
                const existingJklbhs = retainedItemsForWz.map(item => item.jklbh);

                // 找出monitorInitList中存在但保留项中没有的jklbh项（需要补充的）
                const missingItems = sameLevelInitItems.filter(
                    initItem => !existingJklbhs.includes(initItem.jklbh)
                );

                // 补充这些缺失项（结构与addItems一致）
                missingItems.forEach(initItem => {
                    processedRetainedItems.push({
                        wz: wz,
                        check: false, // 新增项默认未勾选
                        jkflbh: initItem.jkflbh,
                        jklbh: initItem.jklbh,
                        jklmc: initItem.jklmc,
                        sjgs: initItem.sjgs,
                        ws: initItem.ws,
                        jkdw: initItem.jkdw,
                        // 其他字段与monitorInitList保持一致
                    });
                });
            });

            console.log(processedRetainedItems, "2222")

            const retainedWzs = processedRetainedItems.map(item => item.wz);
            const needAddWzs = state.formData.selectCheckedList.filter(wz =>
                !retainedWzs.includes(wz)
            );
            const addItems = [] as any[];
            needAddWzs.map(wz => {
                const initItem = state.monitorInitList[wz] as any[];
                initItem.forEach(item => {
                    addItems.push({
                        wz,
                        check: false,
                        jkflbh: item.jkflbh,
                        jklbh: item.jklbh,
                        jklmc: item.jklmc,
                        sjgs: item.sjgs,
                        ws: item.ws,
                        jkdw: item.jkdw,
                    })
                });
            });
            state.formData.monitorList = [...processedRetainedItems, ...needAddWzs]
                .sort((a, b) => {
                    return state.formData.selectCheckedList.indexOf(a.wz) - state.formData.selectCheckedList.indexOf(b.wz);
                });

            console.log(state.formData.monitorList, 'state.formData.monitorList ')
        }

        const handleComponentChange = (e: number[]) => {
            const currentKeys = Object.keys(state.formData.positionList).map(Number);
            const keysToRemove = currentKeys.filter(key => !e.includes(key));
            keysToRemove.forEach(key => {
                delete state.formData.positionList[key];
            });
            const keysToAdd = e.filter(key => !currentKeys.includes(key));
            keysToAdd.forEach(key => {
                state.formData.positionList[key] = {
                    mainid: "",
                    wz: key,
                    zjsl: 0,
                    xingh: "",
                    jh: "",
                    sccj: ""
                };
            });
            initMonitorList();
        }

        // 根据key获取组件名称
        const getComponentName = (key: number): string => {
            const component = state.componentTypes.find((item: ComponentItem) => item.key == key);
            return component?.name || '未知组件';
        };

        return {
            ...toRefs(state),
            ...toRefs(props),
            formRef,
            setData,
            getData,
            verifiyNumberInteger,
            verifyCnAndSpace,

            editable,
            handleComponentChange,
            getComponentName
        }
    },
})
</script>